#生成密钥
import box
import GFarith
import exsystem

S = box.getS()

#key以列表输入
def generate(key):
    for i in range(16):
        key[i] = exsystem.hextoBi(key[i])
    j = '00000001'
    w = {}
    #S = boxS.getS()
    for i in range(4):
        w[i] = key[i*4:i*4+4]
    for i in range(4,44):
        if i%4 == 0:
            w[i] = xo(fg(w[i-1],j), w[i-4])
            j = GFarith.multi(j,'00000010')
        else:
            w[i] = xo(w[i-1],w[i-4])
    for i in range(44):
        for j in range(4):
            w[i][j] = exsystem.tohex(w[i][j])
    return w

#只用于处理此处的特殊形式
def xo(w1, w2):
    w3 = []
    for i in range(4):
        w3.append(GFarith.plus(w1[i],w2[i]))
    return w3

def fg(w, j):
    a = w[1:]
    a.append(w[0])
    for i in range(4):
        a[i] = exsystem.hextoBi(exchange(a[i]))
    a[0] = GFarith.plus(a[0], j)
    return a
    

def exchange(s):
    he = exsystem.tohex(s)
    x = int(he[0],16)
    y = int(he[1],16)
    return S[x][y]
